/* eslint-disable react-hooks/exhaustive-deps */
/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-16 21:46:00
 * @LastEditors: zhouhai zhouhaib@yonyou.com
 * @LastEditTime: 2025-04-10 15:12:15
 */
/* eslint-disable jsx-a11y/anchor-is-valid */
import {
    cleanLogininlog,
    delLogininfor,
    listLogininfor,
} from '@/api/monitor/logininfor';
import { getDictDatasByDictTypes } from '@/api/system/dictData';
import PageDiv from '@/components/PageDiv';
import ResizeTable from '@/components/ResizeTable';
import { useStore } from '@/store';
import { pageInfo } from '@/type.d/ajaxResult';
import { SysLogininforDomain } from '@/type.d/monitor/logininfor';
import { DictDataDomain } from '@/type.d/system';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    QueryFilter,
} from '@ant-design/pro-components';
import { Button, Modal, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import SysLogininforCard from './logininforCard';

import { download } from '@/utils/request';
import { DeleteOutlined } from '@ant-design/icons';
// import './index.less';

const Logininfor: React.FC = () => {
    const { layoutStore } = useStore();

    const actionRef = useRef<ActionType>();
    const queryformRef = useRef<ProFormInstance<SysLogininforDomain>>();
    const [queryValue, setQueryValue] = useState<SysLogininforDomain>({});
    const [tableListDataSource, setTableListDataSource] = useState<SysLogininforDomain[]>([]);

    const [sysCommonStatusOptions, setSysCommonStatusOptions] = useState<any[]>([]);

    const [pageInfo, setPageInfo] = useState<pageInfo>({
        current: 1,
        pageSize: 10,
        total: 0
    });

    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

    const [cardData, setCardData] = useState<SysLogininforDomain>({});
    const [pageStatus, setPageStatus] = useState<'List' | 'Card'>('List');
    const [isedit, setIsedit] = useState<boolean>(false);


    const newdata = {}

    /**
     * 列表字段配置
     */
    const columns: ProColumns<SysLogininforDomain>[] = [
        {
            title: '访问编号',
            dataIndex: 'infoId',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '用户名称',
            dataIndex: 'userName',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '登录地址',
            dataIndex: 'ipaddr',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '登录地点',
            dataIndex: 'loginLocation',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '浏览器',
            dataIndex: 'browser',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '操作系统',
            dataIndex: 'os',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '登录状态',
            dataIndex: 'status',
            valueType: 'select',
            align: 'left',
            width: '50',
            fieldProps: {
                options: sysCommonStatusOptions
            },
            render(dom, entity, index, action, schema) {
                const color = entity.status === '0' ? 'blue' : 'red';
                return <Tag color={color}>{dom}</Tag>
            },
        },
        {
            title: '登录消息',
            dataIndex: 'msg',
            valueType: 'text',
            align: 'left',
            width: '50',
        },
        {
            title: '登录时间',
            dataIndex: 'createTime',
        },
        {
            title: '备注',
            dataIndex: 'remark',
            hideInTable: true
        }
    ];

    const toCard = (data: SysLogininforDomain, isEdit: boolean = false) => {
        setQueryValue(queryformRef.current?.getFieldsValue() || {})
        setPageStatus('Card')
        setCardData({ ...data })
        setIsedit(isEdit)
    }

    const onView = (data: SysLogininforDomain) => {
        toCard(data)
    }


    const onDelete = () => {
        if (selectedRowKeys && selectedRowKeys.length > 0) {
            layoutStore.OpenSpanning()
            delLogininfor(selectedRowKeys.join(',')).then(() => {
                const _data = queryformRef?.current?.getFieldsValue()
                onQuery({ ...pageInfo, ..._data })
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    const onClearn = () => {
        layoutStore.OpenSpanning()
        cleanLogininlog().then(() => {
            setSelectedRowKeys([]);
            setTableListDataSource([])
        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }


    const onExport = () => {
        layoutStore.OpenSpanning()
        download('/monitor/logininfor/export', queryformRef?.current?.getFieldsValue(), `logininfor_${new Date().getTime()}.xlsx`)
        layoutStore.CloseSpanning()
    }


    const headButton = () => {
        return <Space>
            <Button
                icon={<DeleteOutlined />}
                size='small'
                key="delete"
                type="primary"
                onClick={() => Modal.confirm({
                    title: '警告',
                    content: '确定要删除选中的操作日志吗？',
                    onOk: onDelete
                })}
            >
                删除
            </Button>
            <Button
                icon={<DeleteOutlined />}
                size='small'
                key="clean"
                type="primary"
                onClick={() => Modal.confirm({
                    title: '警告',
                    content: '确定要清空所有的操作日志吗？',
                    onOk: onClearn
                })}
            >
                清空
            </Button>
            <Button
                size='small'
                key="export"
                type="primary"
                onClick={onExport}
            >
                导出
            </Button>
        </Space>
    }

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    useEffect(() => {
        layoutStore.OpenSpanning();
        getDictDatasByDictTypes('sys_common_status').then((res) => {
            const data = res.data;
            if (data['sysCommonStatus']) {
                const d: [] = data['sysCommonStatus'];
                setSysCommonStatusOptions(d.map((item: DictDataDomain) => {
                    return {
                        label: item.dictLabel,
                        value: item.dictValue
                    }
                }))

            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })
    }, [])

    //监听分页得操作
    useEffect(() => {
        if (pageInfo.total > 0) {
            //如果原页面有数据，触发查询
            const _data = queryformRef?.current?.getFieldsValue()
            onQuery({...pageInfo,..._data})
        }
    }, [pageInfo.current,pageInfo.pageSize])    


    const onQuery = async (_data: any) => {
        if (_data.createTime) {
            _data.params = {}
            _data.params['beginTime'] = _data.createTime[0];
            _data.params['endTime'] = _data.createTime[1];
            delete _data.createTime
        }

        layoutStore.OpenSpanning();
        listLogininfor(_data).then((res) => {
            setSelectedRowKeys([]);
            setTableListDataSource(res.data)
            if (res.total) {
                setPageInfo({ ...pageInfo, total: res.total })
            }

        }).finally(() => {
            layoutStore.CloseSpanning()
        })

        return _data;
    }

    const onPageChange: (current: number, pageSize: number) => void = (current, pageSize) => {
        setPageInfo({ ...pageInfo, current, pageSize });
    };

    useEffect(() => {
        if (pageStatus === 'List') {
            queryformRef.current?.setFieldsValue(queryValue)
        }
    }, [pageStatus])


    return (
        <PageDiv>{
            pageStatus === 'List' ? <PageDiv>
                <QueryFilter<SysLogininforDomain>
                    defaultCollapsed
                    split
                    span={4}
                    onFinish={(_data) => onQuery({ ...pageInfo, ..._data, current: 1, })}
                    formRef={queryformRef}>
                    <ProFormText key='ipaddr' name="ipaddr" label="登录地址" />
                    <ProFormText key='userName' name="userName" label="用户名称" />
                    <ProFormSelect key='status' name="status"
                        label="登录状态"
                        options={sysCommonStatusOptions}
                    />
                    <ProFormText key='createTime' name="createTime" label="登录时间" />

                    <ProFormText key='loginLocation' name="loginLocation" label="登录地点" hidden />

                    <ProFormText key='browser' name="browser" label="浏览器类型" hidden />

                    <ProFormText key='os' name="os" label="操作系统" hidden />




                </QueryFilter>
                <ResizeTable<SysLogininforDomain>
                    rowKey={'infoId'}
                    onRow={record => {
                        return {
                            onDoubleClick: event => {
                                onView(record)
                            },
                        };
                    }}
                    dataSource={tableListDataSource}
                    actionRef={actionRef}
                    columns={columns}
                    cardBordered
                    revalidateOnFocus={false}
                    pagination={{
                        ...pageInfo,
                        showTitle: false,
                        onChange: onPageChange
                    }}
                    headerTitle={headButton()}
                    rowSelection={rowSelection}
                >
                </ResizeTable>
            </PageDiv> :
                <SysLogininforCard
                    onBack={() => setPageStatus('List')}
                    isedit={isedit}
                    setIsedit={setIsedit}
                    sysCommonStatusOptions={sysCommonStatusOptions}
                    cardData={cardData}
                    newdata={newdata}
                    tableListDataSource={tableListDataSource}
                    setTableListDataSource={setTableListDataSource} />}
        </PageDiv>

    )
}
export default Logininfor;